package thread.futrue;

import java.time.LocalDateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class MyCallableTask implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName()+": MyCallableTask Running....");
        int sum = 0;
        // 计算1...100的和
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        TimeUnit.SECONDS.sleep(5);
        System.out.println(Thread.currentThread().getName()+": MyCallableTask Over");
        return sum;
    }
}
class Test3{
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+"： 开始了..."+LocalDateTime.now());
        MyCallableTask myCallableTask = new MyCallableTask();
        // Callable 任务无法直接交由 Thread 进行调度执行
        FutureTask<Integer> futureTask = new FutureTask<>(myCallableTask);
        Thread thread = new Thread(futureTask);
        thread.start();
        System.out.println(Thread.currentThread().getName()+"： 进行中1..."+LocalDateTime.now());
        try {
            // 主线程睡眠2s
            TimeUnit.SECONDS.sleep(2);
            System.out.println(Thread.currentThread().getName()+"： 进行中2..."+LocalDateTime.now());
            Integer futureResult = futureTask.get();
            System.out.println("result = "+futureResult);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"： Over "+LocalDateTime.now());
    }
}
